package com.hulman.oms.service;

import com.hulman.oms.bean.SemiReport;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.User;
import com.hulman.oms.dao.SemiReportDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.DocUtil;
import com.hulman.oms.util.FileUtil;
import com.hulman.oms.util.StringUtil;
import com.hulman.oms.util.SubjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
public class SemiReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private SemiReportDao semiReportDao;
    @Autowired
    private OnlyOfficeService onlyOfficeService;

    public List<SemiReport> findSemiReports(Map<String, Object> map)
    {
        return semiReportDao.findSemiReports(map);
    }

    public Integer findSemiReportsCount(Map<String, Object> map)
    {
        return semiReportDao.findSemiReportsCount(map);
    }

    public Result findSemiReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = semiReportDao.findSemiReportsCount(map);
        List<SemiReport> data = semiReportDao.findSemiReports(map);
        return new Result(data, count);
    }

    public SemiReport findSemiReportById(Integer id)
    {
        return semiReportDao.findSemiReportById(id);
    }

    public void saveSemiReport(SemiReport semiReport)
    {
        if (semiReport.getId() != null && semiReport.getId() != 0)
        {
            semiReportDao.updateSemiReport(semiReport);
        } else
        {
            semiReportDao.insertSemiReport(semiReport);
        }
    }

    public void deleteSemiReportById(Integer id)
    {
        semiReportDao.deleteSemiReportById(id);
    }

    public void deleteSemiReports(int[] ids)
    {
        semiReportDao.deleteSemiReports(ids);
    }

    /**
     * 检查工作报告是否已生成
     *
     * @param semiReport
     */
    public void checkSemiReport(SemiReport semiReport)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("year", semiReport.getYear());
        map.put("semi", semiReport.getSemi());
        Integer count = semiReportDao.findSemiReportsCount(map);
        if (count > 0)
        {
            throw new IoTException("该半年工作报告已生成");
        }
    }

    public void create(SemiReport semiReport) throws IOException
    {
        checkSemiReport(semiReport);
        User user = SubjectUtil.getUser();
        semiReport.setCreateById(user.getId());
        semiReport.setCreateByName(user.getName());
        int year = semiReport.getYear();
        int semi = semiReport.getSemi();
        LocalDate firstDay = LocalDate.of(year, (semi - 1) * 6 + 1, 1);
        LocalDate lastDay = LocalDate.of(year, semi * 6, 1).with(TemporalAdjusters.lastDayOfMonth());
        Date startDate = Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        semiReport.setStartDate(startDate);
        semiReport.setEndDate(endDate);
        semiReport.setState(0);
        //模板生成报告
        if (semiReport.getSource() == 1)
        {
            Map<String, Object> map = new HashMap<>();
            map.put("reportCycle", semiReport.getReportCycle());
            InputStream inputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("template/semi-report.docx");
            String fileId = StringUtil.uuid() + ".docx";
            Path filePath = Paths.get(fileHome, fileId);
            OutputStream outputStream = Files.newOutputStream(filePath);
            DocUtil.export(inputStream, outputStream, map);
            semiReport.setFileId(fileId);
        }
        semiReportDao.insertSemiReport(semiReport);
        String fileName = semiReport.getReportCycle() + "养护半年报." + FileUtil.parseExtName(semiReport.getFileId());
        onlyOfficeService.create(semiReport.getFileId(), fileName);
    }

    public void submit(Integer id)
    {
        SemiReport semiReport = semiReportDao.findSemiReportById(id);
        semiReport.setState(1);
        semiReport.setEditDate(new Date());
        semiReportDao.updateSemiReport(semiReport);
    }

}
